from django.db import models
from django.utils import timezone
from dvadmin.system.models import CoreModel
import uuid


class TaskStatus(CoreModel):
    """任务状态模型"""
    STATUS_CHOICES = (
        ('pending', '等待中'),
        ('running', '执行中'),
        ('completed', '已完成'),
        ('failed', '执行失败'),
        ('cancelled', '已取消'),
    )
    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    task_id = models.CharField(max_length=100, unique=True, verbose_name="任务编号")
    task_type = models.CharField(max_length=50, verbose_name="任务类型")
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name="状态")
    progress = models.IntegerField(default=0, verbose_name="进度")
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    start_time = models.DateTimeField(null=True, blank=True, verbose_name="开始时间")
    end_time = models.DateTimeField(null=True, blank=True, verbose_name="完成时间")
    parameters = models.JSONField(default=dict, verbose_name="参数")
    result = models.JSONField(null=True, blank=True, verbose_name="结果")
    error_message = models.TextField(null=True, blank=True, verbose_name="错误信息")
    username = models.CharField(max_length=100, verbose_name="用户名")
    
    class Meta:
        db_table = 'web_monitor_task_status'
        verbose_name = '任务状态'
        verbose_name_plural = verbose_name
    
    def __str__(self):
        return f"{self.task_id} - {self.status}"


class TaskExecutionSummary(CoreModel):
    """任务执行总结模型"""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    task_id = models.CharField(max_length=100, unique=True, verbose_name="任务编号")
    summary = models.TextField(verbose_name="执行总结")
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    username = models.CharField(max_length=100, verbose_name="用户名")
    
    class Meta:
        db_table = 'web_monitor_task_summary'
        verbose_name = '任务执行总结'
        verbose_name_plural = verbose_name
    
    def __str__(self):
        return f"{self.task_id} - {self.create_time}"


class HistoricalData(CoreModel):
    """历史数据模型"""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    document_number = models.CharField(max_length=100, verbose_name="单据号")
    push_time = models.DateTimeField(verbose_name="推送时间")
    validation_result = models.CharField(max_length=20, verbose_name="校验结果")
    detailed_error = models.TextField(null=True, blank=True, verbose_name="详细错误信息")
    username = models.CharField(max_length=100, verbose_name="用户名")
    
    class Meta:
        db_table = 'web_monitor_historical_data'
        verbose_name = '历史数据'
        verbose_name_plural = verbose_name
        ordering = ['-push_time']
    
    def __str__(self):
        return f"{self.document_number} - {self.push_time}"


class ValidationCache(CoreModel):
    """校验缓存模型"""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    username = models.CharField(max_length=100, verbose_name="用户名")
    cache_key = models.CharField(max_length=255, verbose_name="缓存键")
    cache_value = models.JSONField(verbose_name="缓存值")
    expire_time = models.DateTimeField(verbose_name="过期时间")
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    
    class Meta:
        db_table = 'web_monitor_validation_cache'
        verbose_name = '校验缓存'
        verbose_name_plural = verbose_name
        unique_together = ('username', 'cache_key')
    
    def __str__(self):
        return f"{self.username} - {self.cache_key}"


class TaskContext(CoreModel):
    """任务上下文模型"""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    task_id = models.CharField(max_length=100, unique=True, verbose_name="任务编号")
    username = models.CharField(max_length=100, verbose_name="用户名")
    password = models.CharField(max_length=255, verbose_name="密码")
    headless_mode = models.BooleanField(default=True, verbose_name="无头模式")
    start_position = models.IntegerField(default=1, verbose_name="开始位置")
    start_service_request_number = models.CharField(max_length=100, null=True, blank=True, verbose_name="开始服务请求号")
    auto_loop_run = models.BooleanField(default=False, verbose_name="自动循环运行")
    task_running_flag = models.BooleanField(default=True, verbose_name="任务运行标识")
    context_data = models.JSONField(default=dict, verbose_name="上下文数据")
    
    class Meta:
        db_table = 'web_monitor_task_context'
        verbose_name = '任务上下文'
        verbose_name_plural = verbose_name
    
    def __str__(self):
        return f"{self.task_id} - {self.username}"


class ValidationResult(models.Model):
    """
    OCR制证校验结果模型
    根据 DDL 文件独立创建，不继承 CoreModel
    """
    id = models.BigAutoField(primary_key=True, verbose_name="ID")
    user_id = models.CharField(max_length=50, verbose_name="用户ID", help_text="用户ID")
    code = models.CharField(max_length=50, verbose_name="单据号", help_text="单据号")
    val_result = models.JSONField(null=True, blank=True, verbose_name="校验结果", help_text="校验概览结果（JSON格式）")
    error_msg = models.JSONField(null=True, blank=True, verbose_name="详细错误信息", help_text="详细错误信息（JSON格式）")
    if_pass = models.BooleanField(verbose_name="是否通过校验", help_text="是否通过校验", db_column='if_pass')
    push_time = models.DateTimeField(verbose_name="推送时间", help_text="推送时间")
    created_time = models.DateTimeField(auto_now_add=True, null=True, blank=True, verbose_name="创建时间", help_text="创建时间")
    updated_time = models.DateTimeField(auto_now=True, null=True, blank=True, verbose_name="更新时间", help_text="更新时间")
    
    class Meta:
        db_table = 'validation_result'
        verbose_name = 'OCR制证校验结果'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['push_time'], name='idx_push_time'),
            models.Index(fields=['user_id', 'code'], name='idx_user_code'),
            models.Index(fields=['user_id', 'push_time'], name='idx_user_time'),
        ]
    
    def __str__(self):
        return f"{self.code} - {self.user_id}"


class ProcessedDocument(CoreModel):
    """已处理单据模型"""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    task_id = models.CharField(max_length=100, verbose_name="任务编号")
    document_number = models.CharField(max_length=100, verbose_name="单据号")
    process_status = models.CharField(max_length=20, verbose_name="处理状态")
    process_time = models.DateTimeField(auto_now_add=True, verbose_name="处理时间")
    username = models.CharField(max_length=100, verbose_name="用户名")
    
    class Meta:
        db_table = 'web_monitor_processed_document'
        verbose_name = '已处理单据'
        verbose_name_plural = verbose_name
        ordering = ['-process_time']
    
    def __str__(self):
        return f"{self.document_number} - {self.process_status}"